const moment = require('moment');

const commonUtils = {
    /**
     * @desc 获取一个uuid
     * @author cbl
     * @date 2018/4/16
     */
    genUUID: () => {
        const s = [];
        const hexDigits = "0123456789abcdef";
        for (let i = 0; i < 32; i++) {
            s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[14] = "4";
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
        s[8] = s[13] = s[18] = s[23];

        const uuid = s.join("");
        return uuid;
    },

    /**
     * 生成指定位数的随机数
     * @param n
     * @returns {string}
     */

    createRandomNumber: (n) => {
        let t = '';
        for (let i = 0; i < n; i++) {
            let a = Math.floor(Math.random() * 10);
            if (i == 0) {
                if (a == 0) {
                    a = '1';
                }
            }
            t += a + '';
        }
        return t;
    },

    /**
     * 生成订单号
     * @returns {string|ServerResponse}
     */
    createOrderNumber: () => {
        return moment().format('YYYYMMDDhhmmssSSS') + this.createRandomNumber(3);
    },

    /**
     * 获取请求端的IP地址
     * @author cbl
     * @date 2018/4/17
     */
    getClientIp: (req) => {
        let ip = req.headers['x-forwarded-for'] ||
            req.ip ||
            req.connection.remoteAddress ||
            req.socket.remoteAddress ||
            req.connection.socket.remoteAddress || '';
        if (ip.split(',').length > 0) {
            ip = ip.split('.')[0];
        }
        return ip;
    },
    /**
     * 得到用来近似匹配的值
     * @param text 匹配的值
     * @returns {string|string|*|string}
     * @apiVersion 作者：cbl
     */
    getLikeValue: (text) => {
        let finish = '\'%\'';
        for (let i = 0; i < text.length; i++) {
            finish += (',' + '\'' + text.substr(i, 1) + '\'' + ',' + '\'%\'');
        }
        return finish;
    },

    /**
     * @desc 将json或string对转为string并最多截取500字符
     * @author cbl
     * @date 2018/4/17
     */
    toMyString: (obj) => {
        let resultString = "";
        //判断obj是否为json对象
        let isJson = typeof(obj) === "object" && Object.prototype.toString.call(obj).toLowerCase() === "[object object]" && !obj.length;
        if (isJson) {
            resultString = JSON.stringify(obj);
        } else if (typeof obj === "string") {
            resultString = obj;
        } else {
            resultString = "";
        }
        //如返回的body的内容长度大于500，则只截取500字符打印日志
        if (resultString.length > 500) {
            resultString = resultString.substring(0, 500);
        }
        return resultString;
    }
};
module.exports = commonUtils;